const express = require('express');
const router = express.Router();
const { Setting } = require('../../models');
const { success, failure } = require('../../utils/response');
const {NotFound} = require('http-errors');

// 查询单条数据
router.get('/',async(req,res)=>{
    try {
        const setting = await getSetting(req);
        success(res, '获取设置数据成功', setting);
    } catch (error) {
        failure(res, error);
    }
})

// 更新数据
router.put("/",async(req,res)=>{
    try {
        const body = await filterBody(req)
        const setting = await getSetting(req);
        await setting.update(body)
        success(res, '更新设置数据成功', setting);
    } catch (error) {
        failure(res, error);
    }
})

/**
 * 公共方法：白名单过滤
 * @param {*} req 
 * @returns 
 */
async function filterBody(req) {
    return {
        name: req.body.name,
        icp: req.body.icp,
        copyright: req.body.copyright,
    }
}

/**
 * 公共方法：获取设置数据
 * @param {*} req 
 * @returns 
 */
async function getSetting(req) {
    const setting = await Setting.findOne()
    if (!setting) {
        throw new NotFound('没有找到设置数据')
    }
    return setting;
}
module.exports = router;